
package com.android.finaltracer.gps;

import android.content.Context;
import android.util.Log;

import com.android.finaltracer.engine.EventNotify;
import com.android.finaltracer.gps.PositionListener.PositionCallBack;
import com.android.finaltracer.model.PositionInfo;

/**
 * Gps assist module for mobile device to fetch its location through GPS/AGPS
 * 
 * @author zhuhy1
 */
public class Gps implements PositionCallBack {
    private static final String TAG = "GpsFnc";

    // position listener
    private PositionListener mListener;
    // last position
    private PositionInfo mPosition;
    // Context
    private Context mContext;

    private EventNotify m_Notify;

    private static Gps instance;

    private int gpsUsedCount;

    /**
     * Constructor
     */
    private Gps(Context context, EventNotify E_Notify) {
        mContext = context;
        m_Notify = E_Notify;
        gpsUsedCount = 0;
        mListener = new PositionListener(mContext, this);
    }

    public static Gps getInstance(Context context, EventNotify E_Notify) {
        if (instance == null) {
            instance = new Gps(context, E_Notify);
        }
        return instance;
    }

    /**
     * start module
     */
    public boolean start() {
        Log.d(TAG, "start");
        // if (mListener == null) {
        // mListener = new PositionListener(mContext, this);
        // }
        if (mListener != null) {
            Log.d(TAG, "listener run");
            mListener.start();
            gpsUsedCount++;
        }
        return true;
    }

    /**
     * stop module
     */
    public void stop() {
        Log.d(TAG, "stop");
        if (gpsUsedCount > 0) {
            gpsUsedCount--;
        }
        if (mListener != null && gpsUsedCount == 0) {
            mListener.stop();
        }
    }

    /**
     * get last position
     */
    public PositionInfo getGpsPosition() {

        return mPosition;

    }

    /*
     * (non-Javadoc)
     * @see com.android.FinalTracer.GPS.PositionListener.PositionCallBack#
     * onCurrentPosition(com.android.FinalTracer.GPS.PositionInfo)
     */
    @Override
    public void onCurrentPosition(PositionInfo position) {
        // TODO Auto-generated method stub
        if (position != null) {
            Log.d(TAG, "position changed");
            mPosition = position;
            m_Notify.localGpsPositionChanged(mPosition);
        }
    }
}
